/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ucuenca.paginaasos.uimanager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Marcelo
 */
@ManagedBean(name = "fileUploadController2")
@RequestScoped
public class UploadFilesBean {

    private Part file1;

    private String logEventos;

    private static final int BUFFER_SIZE = 6124;
    private String folderToUpload;

    private void addLog(String txt) {
        logEventos += txt + "\n";
        RequestContext.getCurrentInstance().update("frm");
    }

    public void handleFileUpload(FileUploadEvent event) {

        addLog("------------");
        File f = new File("test.txt");
        addLog("path: " + f.getAbsolutePath());

        ExternalContext extContext
                = FacesContext.getCurrentInstance().getExternalContext();
        File result = new File(extContext.getRealPath("//subidas//" + event.getFile().getFileName()));

        addLog(extContext.getRealPath("//subidas//" + event.getFile().getFileName()));

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();

            if (inputStream != null) {
                addLog("no nulo");
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                        "NO ES NULO", ""));
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "ES NULO", ""));
                addLog("es nulo");
                return;
            }

            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }

            fileOutputStream.close();
            inputStream.close();

            FacesMessage msg
                    = new FacesMessage("File Description", "file name: "
                            + event.getFile().getFileName() + "file size: "
                            + event.getFile().getSize() / 1024 + " Kb content type: "
                            + event.getFile().getContentType() + ".");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            e.printStackTrace();

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    e.getLocalizedMessage(), ""));
        }

    }

    public String upload() throws IOException {

        String nombreArchivo = getFilename(file1);
        ExternalContext extContext
                = FacesContext.getCurrentInstance().getExternalContext();
        //File result = new File(extContext.getRealPath("//subidas//" + nombreArchivo));

        String rp = extContext.getRealPath("//subidas//" + nombreArchivo);

        addLog("rp: " + rp);
        File result = new File(rp);

        String pathFinal = result.getAbsolutePath();

        addLog("pathfinal: " + pathFinal);

        InputStream inputStream = file1.getInputStream();
        try {
            result.createNewFile();
            addLog("creado");
        } catch (Exception e) {
            addLog("err al crear: " + e.getLocalizedMessage());
        } 

        if (inputStream != null) {
            addLog("no nulo");
        } else {
            addLog("nulo");
        }
        try {
            FileOutputStream outputStream = new FileOutputStream(result);

            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while (true) {
                bytesRead = inputStream.read(buffer);
                if (bytesRead > 0) {
                    outputStream.write(buffer, 0, bytesRead);
                } else {
                    break;
                }
            }
            outputStream.close();
            inputStream.close();

            addLog("OOOOOOOOOOOK");
        } catch (Exception e) {
            addLog("exception: " + e.getLocalizedMessage());
        }

        return "";
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.  
            }
        }
        return null;
    }

    public String getLogEventos() {
        return logEventos;
    }

    public void setLogEventos(String logEventos) {
        this.logEventos = logEventos;
    }

    public Part getFile1() {
        return file1;
    }

    public void setFile1(Part file1) {
        this.file1 = file1;
    }
}
